<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="./js/promiseAjax.js"></script>
    <script src="./js/cookie.js"></script>
</head>
<body>
    <form action="">
        用户名 <input type="text" name="username" >
        <br>
        密码<input type="password" name="password" >
        <br>
        <input type="submit">
    </form>
</body>
<script>
    document.querySelector('form').onsubmit=function(){
        var username=document.querySelector('[name="username"]').value
        var password=document.querySelector('[name="password"]').value
        request({
            url:'/api/users/login',
            method:'post',
            data:{
                username,
                password
            }


        }).then(res=>{
            console.log(res)
            var {error_code,msg}=res
            alert(msg)
            if(error_code===0){
                //设置 cookie
                setCookie('username',username,1000000)
                setCookie('userid',res.data.userid,1000000)
                //本地存token
                localStorage.setItem('token',res.data.token)
                //不一定往首页跳，如果本地有购物车那个存起来的地址就往那边跳
                var url=localStorage.getItem('url')
                if(url){
                    //先把本地存储的url删了  下面的那个url是变量 不是指本地存储的那个url
                    localStorage.removeItem('url')
                    location.href=url
                }else{
                    location.href='./index.html'
                }
                
                
            }
        })


        return false
    }
</script>
</html>